package com.example.musicplayer

import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.example.musicplayer.adapter.TabAdapter
import com.example.musicplayer.model.Banner
import com.example.musicplayer.model.Music
import com.example.musicplayer.model.RecommendMusic
import com.example.musicplayer.service.BannerListCallback
import com.example.musicplayer.service.MusicListCallback
import com.example.musicplayer.service.RecommendMusicListCallback
import com.example.musicplayer.utils.HttpUtils
import com.example.musicplayer.utils.HttpUtils.HttpCallback
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import java.io.IOException

class MainActivity : AppCompatActivity() {

    private val baseUrl = "http://121.37.40.55:3000/"
    private var musicTitleTextView: TextView? = null
    private var musicSingerTextView: TextView? = null
    private var musicCoverImageView: ImageView? = null
    private var playPauseButton: ImageView? = null
    private var nextButton: ImageView? = null
    private var playMenuButton: ImageView? = null
    private val bannerList: MutableList<Banner> = ArrayList()
    private val musicList: MutableList<Music> = ArrayList()
    private val recommendMusicList: MutableList<RecommendMusic> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
        val viewPager2 = findViewById<ViewPager2>(R.id.view_pager)
        musicTitleTextView = findViewById(R.id.music_title)
        musicSingerTextView = findViewById(R.id.music_singer)
        musicCoverImageView = findViewById(R.id.music_cover)
        playPauseButton = findViewById(R.id.play_pause_button)
        nextButton = findViewById(R.id.next_button)
        playMenuButton = findViewById(R.id.play_menu_button)
        playMenuButton?.setOnClickListener {
            // 不推荐使用，不方便维护
            viewPager2.setCurrentItem(2, true)
        }

        // 设置适配器
        val tabAdapter = TabAdapter(
            this, bannerList, musicTitleTextView!!,
            musicSingerTextView!!, musicCoverImageView!!,
            playPauseButton!!,
            musicList, recommendMusicList
        )

        val playlistFragment = tabAdapter.getPlaylistFragment()


        nextButton?.setOnClickListener {
            playlistFragment.nextMusic()
        }

        viewPager2.adapter = tabAdapter

        TabLayoutMediator(tabLayout, viewPager2) { tab: TabLayout.Tab, position: Int ->
            when (position) {
                0 -> tab.text = "音乐推荐"
                1 -> tab.text = "播放器"
                2 -> tab.text = "播放列表"
            }
        }.attach()
        getBanner(object : BannerListCallback {
            override fun onBannerListLoaded(bannerList: MutableList<Banner>?) {
                this@MainActivity.bannerList.clear()
                this@MainActivity.bannerList.addAll(bannerList!!)
            }
        })

        getMusicList(object : MusicListCallback {
            override fun onMusicListLoaded(musicList: MutableList<Music>?) {
                this@MainActivity.musicList.clear()
                this@MainActivity.musicList.addAll(musicList!!)
            }
        })

        getRecommendMusic(object : RecommendMusicListCallback {
            override fun onMusicListLoaded(recommendMusicList: MutableList<RecommendMusic>?) {
                this@MainActivity.recommendMusicList.clear()
                this@MainActivity.recommendMusicList.addAll(recommendMusicList!!)
            }
        })


    }


    private fun getBanner(callback: BannerListCallback?) {
        HttpUtils[baseUrl + "banner", object : HttpCallback {
            override fun onSuccess(response: String?) {
                try {
                    val gson = Gson()
                    val listType = object : TypeToken<MutableList<Banner>?>() {}.type
                    val bannerList = gson.fromJson<MutableList<Banner>>(response, listType)

                    callback?.onBannerListLoaded(bannerList)
                } catch (e: JsonSyntaxException) {
                    throw RuntimeException(e)
                }
            }

            override fun onError(code: Int, message: String?) {
                System.err.println("GET 请求错误: $code, $message")
            }

            override fun onFailure(e: IOException?) {}
        }]
    }

    private fun getMusicList(callback: MusicListCallback?) {
        HttpUtils[baseUrl + "list", object : HttpCallback {
            override fun onSuccess(response: String?) {
                try {
                    val gson = Gson()
                    val listType = object : TypeToken<MutableList<Music>?>() {}.type
                    val musicList = gson.fromJson<MutableList<Music>>(response, listType)

                    callback?.onMusicListLoaded(musicList)
                } catch (e: Exception) {
                    e.printStackTrace()
                    println("解析音乐列表数据失败: " + e.message)
                }
            }

            override fun onError(code: Int, message: String?) {
                println("GET 请求错误: $code, $message")
            }

            override fun onFailure(e: IOException?) {
                e!!.printStackTrace()
            }
        }]
    }

    /**
     * 获取推荐音乐
     */
    private fun getRecommendMusic(callback: RecommendMusicListCallback?) {
        HttpUtils[baseUrl + "rec", object : HttpCallback {
            override fun onSuccess(response: String?) {
                try {
                    val gson = Gson()
                    val listType = object : TypeToken<MutableList<RecommendMusic>?>() {}.type
                    val list = gson.fromJson<MutableList<RecommendMusic>>(response, listType)

                    callback?.onMusicListLoaded(list)
                } catch (e: Exception) {
                    e.printStackTrace()
                    println("解析推荐音乐列表数据失败: " + e.message)
                }
            }

            override fun onError(code: Int, message: String?) {
                println("GET 请求错误: $code, $message")
            }

            override fun onFailure(e: IOException?) {
                e!!.printStackTrace()
            }
        }]
    }

}